package com.icms.core.dbutil;

import java.io.IOException;
import java.io.InputStream;
import java.sql.SQLException;
import java.util.Properties;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidDataSourceFactory;
import com.alibaba.druid.pool.DruidPooledConnection;

public class DBConnectionPool {
	
	private static DBConnectionPool databasePool = null;
	private static DruidDataSource dds ;
	
	private DBConnectionPool() {}
	
	static {
		Properties prop = loadPropFile("db.properties") ;
		try {
			dds = (DruidDataSource) DruidDataSourceFactory.createDataSource(prop) ;
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public static synchronized DBConnectionPool getInstance() {
		if (null == databasePool) {
			databasePool = new DBConnectionPool();
		}
		return databasePool;
	}
	
	public DruidDataSource getDataSource() {
		return dds ;
	}
	
	public static DruidPooledConnection getConnection() {
		try {
			return dds.getConnection() ;
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return null;
	}
	
	/**
	 * 加载属性文件
	 * @param fullname 文件名称
	 * @return
	 */
	public static Properties loadPropFile(String fullname) {
		try {
			ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader() ;
			InputStream resourceAsStream = contextClassLoader.getResourceAsStream(fullname) ;
			Properties prop = System.getProperties() ;
			prop.load(resourceAsStream) ;
			
			return prop ;
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}
	
}
